<template>
  <view class="container">
    <view class="upload-tips">上传格式：支持jpg/png/jpeg/doc/docx/pdf</view>
    <view class="contrac-list">
      <ve-form :model="form" ref="formRef" :rules="rules" layout="vertical">
        <contract-pane
          v-for="(contractItem, index) in form.contractList"
          :contractIndex="index"
          :key="index"
          mode="card"
          :contractItem="contractItem"
        />
      </ve-form>
    </view>
    <ve-bottom-box size="mini">
      <ve-button type="primary" :loading="okLoading" @click="onConfirm" size="long">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { ref, computed } from 'vue'
  import { contractListAPI, uploadContractAPI } from '@/api/order/lOrder'
  import { onLoad } from '@dcloudio/uni-app'
  import contractPane from './components/contract/contract-pane.vue'
  import useToast from '@/hooks/useToast'
  import { handleContracList } from './tools'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'

  const form = ref({})
  const orderId = ref()
  onLoad((options) => {
    orderId.value = options.id
    // 获取订单详情
    contractListAPI({ id: orderId.value }).then((res) => {
      form.value.contractList = handleContracList(res.result)
    })
  })

  // rules
  const rules = computed(() => {
    let contractList = form.value.contractList || []
    let tempRules = {}
    contractList.forEach((contractItem, contractIndex) => {
      if (contractItem.contractFileId) {
        tempRules[`contractList.${contractIndex}.contractNo`] = { required: true, message: '请输入合同编号' }
      }
    })
    return tempRules
  })

  const formRef = ref()
  const okLoading = ref(false)
  // 确认修改
  const onConfirm = () => {
    formRef.value.validate((valid, errors) => {
      if (valid) {
        okLoading.value = true
        const param = {
          contractList: form.value.contractList,
          id: orderId.value,
        }
        uploadContractAPI(param)
          .then(() => {
            useToast({
              title: '修改成功',
            }).then(() => {
              useLoadDataAndHotUpdateNavigateBack()
            })
          })
          .catch(() => {
            okLoading.value = false
          })
      }
    })
  }
</script>

<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    background: #f7f8fa;
  }
  .contrac-list {
    padding: 24rpx;
  }
  .upload-tips {
    height: 80rpx;
    line-height: 80rpx;
    background: #e8f3ff;
    border-radius: 4rpx 4rpx 4rpx 4rpx;
    color: #1d2129;
    font-size: 24rpx;
    color: #1d2129;
    padding: 0 32rpx;
  }
</style>
